/*
 * ManejadorPermiso.java
 */
package servlets;

import beans.Modulo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

import dbUtil.*;
import iteradores.*;
import beans.Permiso;
import beans.Rol;

/**
 *
 * @author Administrador
 */
public class ManejadorPermisoaRol extends HttpServlet {

    private String nombreModulo = "permisoarol";
    private IteradorUsuario usuarioActual;

    /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html");
        response.setCharacterEncoding("windows-1252");
        PrintWriter out = response.getWriter();
        String url = null;

        try {
            //Datos del usuario actual de la sesion, si esto es nulo significa
            //que aun no hizo login
            usuarioActual = (IteradorUsuario) request.getSession().getAttribute("usuarioActual");
            if (usuarioActual == null) {
                url = "login.jsp"; //Volver a loguearse

            } else {
                // Obtiene la conexión a la base de datos de la sesión
                Connection con = (Connection) request.getSession().getAttribute("ConexionBd");
                //Obtiene la operación a realizar 
                String str_op = request.getParameter("op");

                if (str_op != null) {
                    //Objeto que averigua si el usuario tiene permisoarol para acceder al servlet.
                    PgAbm testPermiso = new PgAbm();
                    testPermiso.setCon(con);

                    usuarioActual.getReset();
                    usuarioActual.getNext();
                    if (testPermiso.tienePermiso(nombreModulo,
                            usuarioActual.getNombreusuario(),
                            str_op.substring(0, 6))) {
                        url = "permisoarol.jsp?modo=ASIGNA";

                        if (str_op.equals("SELECT")) {
                            url = this.select_data(con, request, response);
                        } else if (str_op.equals("INSERT")) {
                            url = this.insert_data(con, request, response);
                        } else if (str_op.equals("UPDATE")) {
                            url = this.update_data(con, request, response);
                        } else if (str_op.equals("DELETE")) {
                            url = this.delete_data(con, request, response);
                        }
                    } else {
                        url = "sinpermiso.jsp";
                    }
                } else {
                    url = "admin.jsp";
                }
            }
            mostrar_pagina(url, request, response);
        } catch (Exception e) {
            e.printStackTrace(out);
        }
    }

    public void mostrar_pagina(String url, HttpServletRequest req, HttpServletResponse resp)
            throws Exception {
        RequestDispatcher disp = req.getRequestDispatcher(url);
        resp.setHeader("Cache-Control", "no-cache");
        resp.setCharacterEncoding("windows-1252");
        resp.setHeader("Pragma", "no-cache");
        resp.setIntHeader("Expires", 0);
        disp.forward(req, resp);
    }

    public DBConfig getDataBaseConfig() {
        ServletContext scon = getServletContext();
        DBConfig dc = new DBConfig();
        dc.setDbname(scon.getInitParameter("dbname"));
        dc.setServer(scon.getInitParameter("dbserver"));
        dc.setUser(scon.getInitParameter("dbuser"));
        dc.setPass(scon.getInitParameter("dbpass"));
        return dc;
    }

    //<editor-fold defaultstate="collapsed" desc="Métodos ABM (SELECT, INSERT, UPDATE y DELETE).">
    public String select_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "permisoarol.jsp?modo=ASIGNA";
        String idmodulo = request.getParameter("idmodulo");
        String idrol = request.getParameter("idrol");
        String modulos = (String) request.getAttribute("Modulos");
        String roles = (String) request.getAttribute("Roles");

        String sql = "";
        Statement stm = null;

        con.setAutoCommit(false);

        if (idmodulo != null && idrol != null) {
            sql = "select (select idrol from rol where idrol = " + idrol + ") as idrol, mp.idmodulo, m.descripcion as modulo, " +
                    " mp.idpermiso, p.descripcion as permiso " +
                    " from modulo_permiso mp " +
                    " join modulo m on mp.idmodulo = m.idmodulo " +
                    " join permiso p on mp.idpermiso = p.idpermiso " +
                    " where mp.idmodulo = " + idmodulo + 
                    " and mp.idpermiso not in (select distinct idpermiso from rol_modulo_permiso rmp " + 
                    " where idmodulo = " + idmodulo +" and idrol = " + idrol + ")" +
                    " order by m.descripcion, p.descripcion";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            ResultSet result = stm.executeQuery(sql);
            IteradorModuloPermiso mp = new IteradorModuloPermiso(result);
            request.setAttribute("ModulosPermisos", mp);
        
            sql = " select rmp.idrol, r.descripcion as rol, rmp.idmodulo, m.descripcion as modulo, " +
                    " rmp.idpermiso, p.descripcion as permiso " +
                    " from rol_modulo_permiso rmp " +
                    " join rol r on rmp.idrol = r.idrol " +
                    " join modulo_permiso mp on rmp.idmodulo = mp.idmodulo and rmp.idpermiso = mp.idpermiso " +
                    " join modulo m on mp.idmodulo = m.idmodulo " +
                    " join permiso p on mp.idpermiso = p.idpermiso " +
                    " where r.idrol = " + idrol +
                    " and m.idmodulo = " + idmodulo +
                    " order by modulo, permiso ";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);
            
            System.out.println(sql);
            ResultSet result2 = stm.executeQuery(sql);

            IteradorRolModuloPermiso rmp = new IteradorRolModuloPermiso(result2);
            request.setAttribute("RolModulosPermisos", rmp);
        }
        
        if (modulos == null ) {
            Modulo modulo = new Modulo();
            modulo.setCon(con);
            modulo.getModulos();

            IteradorModulo itm = (IteradorModulo) modulo.getIteratorAll();
            request.setAttribute("Modulos", itm);
        }
        if (roles == null) {
            Rol rol = new Rol();
            rol.setCon(con);
            rol.getRoles();
            IteradorRol it = (IteradorRol) rol.getIteratorAll();
            request.setAttribute("Roles", it);
        }
        return url;
    }

    public String insert_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "permisoarol.jsp?modo=INSERT";
        String idmodulo = request.getParameter("idmodulo");
        String idrol = request.getParameter("idrol");
        String idpermiso = request.getParameter("idpermiso");

        String sql = "";
        Statement stm = null;

        con.setAutoCommit(false);

        if (idmodulo != null && idrol != null) {
            sql = "INSERT INTO rol_modulo_permiso SELECT "+ idrol + "," + idmodulo + ", " + idpermiso + ";";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            int cant = stm.executeUpdate(sql);
            System.out.println("Fila ingresada: " + cant);
            con.commit();
            
            url = select_data(con, request, response);
        }
        return url;
    }

    public String update_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "permisoarol.jsp?modo=UPDATE";

        String action = request.getParameter("action");
        String idpermiso = request.getParameter("idpermiso");

        Permiso nc = (Permiso) request.getSession().getAttribute("lastBeanPermiso");
        if (nc != null) {
            nc.setCon(con);
            if (idpermiso != null) {
                nc.setIdPermiso(idpermiso);
            }
            nc.setSearchMode(PgAbm.SEARCH_EXACT);
            nc.load_data();
            IteradorPermiso it = (IteradorPermiso) nc.getIterator();
            request.setAttribute("Permisos", it);
        }

        if ((action != null) && action.equalsIgnoreCase("do")) {
            String str_idPermiso = request.getParameter("idpermiso");

            if ((str_idPermiso != null) && (str_idPermiso.length() > 0)) {
                int idPermiso = 0;
                idPermiso = Integer.parseInt(str_idPermiso);
            } else {
                throw new Exception("El id del permisoarol que desea modificar no es válido.");
            }
            con.setAutoCommit(false);

            Permiso permisoarol = new Permiso();
            permisoarol.setCon(con);
            permisoarol.setIdPermiso(str_idPermiso);
            permisoarol.setAllParams(request);
            permisoarol.update_data();

            /* 
             * Aplicamos nuevamente los filtros anteriores para refrescar los
             * datos en pantalla.
             */
            nc = (Permiso) request.getSession().getAttribute("lastBeanPermiso");
            if (nc == null) {
                nc = new Permiso();
            }
            nc.setCon(con);
            nc.load_data();
            IteradorPermiso it = (IteradorPermiso) nc.getIterator();
            request.setAttribute("Permisos", it);

            con.commit();
            url = "permisoarol.jsp?modo=SELECT&msg=UPDTDONE";
        }
        return url;
    }

    public String delete_data(Connection con, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = "";
        String idmodulo = request.getParameter("idmodulo");
        String idrol = request.getParameter("idrol");
        String idpermiso = request.getParameter("idpermiso");

        String sql = "";
        Statement stm = null;

        con.setAutoCommit(false);

        if (idmodulo != null && idrol != null) {
            sql = "DELETE FROM rol_modulo_permiso where idrol = "+ idrol + " and idmodulo = " + idmodulo + " and idpermiso = " + idpermiso + ";";

            stm = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
                    ResultSet.CONCUR_READ_ONLY);

            System.out.println(sql);
            int cant = stm.executeUpdate(sql);
            System.out.println("Fila borrada: " + cant);
            con.commit();
            
            url = select_data(con, request, response);
        }
        return url;
    }
    //</editor-fold>
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
    }

    @Override
    public void destroy() {
    }

    /** Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     */
    @Override
    public String getServletInfo() {
        return "Este servlet maneja las peticiones sobre la tabla Permiso";
    }
// </editor-fold>
}
